# Copyright 2026 OpenHW Group
# SPDX-License-Identifier: Apache-2.0
#
# Composite Action: Setup CVA6 Simulation Environment
# Handles caching, optional tool installation, and environment setup for CVA6 CI jobs

name: 'Setup CVA6 Environment'
description: 'Cache/restore tools and prepare the CVA6 simulation environment'

inputs:
  install-tools:
    description: 'Run ci/setup.sh to install tools if cache miss'
    required: false
    default: 'true'

outputs:
  toolchain-cache-hit:
    description: 'Whether RISC-V toolchain cache was hit'
    value: ${{ steps.cache-toolchain.outputs.cache-hit }}
  verilator-cache-hit:
    description: 'Whether Verilator cache was hit'
    value: ${{ steps.cache-verilator.outputs.cache-hit }}
  spike-cache-hit:
    description: 'Whether Spike cache was hit'
    value: ${{ steps.cache-spike.outputs.cache-hit }}

runs:
  using: 'composite'
  steps:
    # Step 1: Get submodule hash for Spike cache key
    - name: Get core-v-verif submodule hash
      id: submodule-hash
      shell: bash
      run: |
        cd verif/core-v-verif
        echo "hash=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT

    # Step 2: Cache RISC-V Toolchain
    - name: Cache RISC-V Toolchain
      id: cache-toolchain
      uses: actions/cache@v6
      with:
        path: tools/riscv-toolchain/
        key: ${{ runner.os }}-toolchain-${{ hashFiles('ci/install-toolchain.sh') }}
        # restore-keys: |
        #   ${{ runner.os }}-toolchain-

    # Step 3: Cache Verilator
    - name: Cache Verilator
      id: cache-verilator
      uses: actions/cache@v6
      with:
        path: tools/verilator/
        key: ${{ runner.os }}-verilator-${{ hashFiles('verif/regress/install-verilator.sh') }}
        # restore-keys: |
        #   ${{ runner.os }}-verilator-

    # Step 4: Cache Spike
    - name: Cache Spike
      id: cache-spike
      uses: actions/cache@v6
      with:
        path: tools/spike/
        key: ${{ runner.os }}-spike-${{ hashFiles('verif/regress/install-spike.sh') }}-${{ steps.submodule-hash.outputs.hash }}
        # restore-keys: |
        #   ${{ runner.os }}-spike-${{ hashFiles('verif/regress/install-spike.sh') }}-
        #   ${{ runner.os }}-spike-

    # Step 5: Install tools if cache miss and requested
    - name: Setup tools (if cache miss)
      if: |
        inputs.install-tools == 'true' && (
          steps.cache-toolchain.outputs.cache-hit != 'true' ||
          steps.cache-verilator.outputs.cache-hit != 'true' ||
          steps.cache-spike.outputs.cache-hit != 'true'
        )
      shell: bash
      run: |
        set -x
        ci/setup.sh

    # Step 6: Setup environment variables
    - name: Setup environment variables
      shell: bash
      run: |
        echo "RISCV=$(pwd)/tools/riscv-toolchain" >> $GITHUB_ENV
        echo "$(pwd)/tools/verilator/bin" >> $GITHUB_PATH
        echo "$(pwd)/tools/spike/bin" >> $GITHUB_PATH
